package com.gjintel.framework.register.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.activiti.engine.IdentityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.gjintel.framework.constant.ActivitiMap;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.register.dao.RegisterUserDao;
import com.gjintel.framework.register.model.DepositCategory;
import com.gjintel.framework.register.model.RegisterCategory;
import com.gjintel.framework.register.model.RegisterUser;
import com.gjintel.framework.register.service.IRegisterUserService;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.user.model.UserRole;
import com.gjintel.framework.user.service.IUserService;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.framework.util.Rsp;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.service.impl.BaseServiceImpl;
import com.gjintel.sdk.util.MD5Lock;

@Service("registerUserService")
public class RegisterUserServiceImpl extends BaseServiceImpl implements
		IRegisterUserService {
	@Autowired
	private RegisterUserDao rUserDao;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private IUserService userService;

	@Override
	@Transactional
	public String saveRegisterUser(RegisterUser loginUser) {
		String result = "";
		loginUser.setType(ActivitiMap.BIDDER_ID);
		loginUser.setPwd(MD5Lock.lock(loginUser.getPwd()));
		loginUser.setCreateTime(new Date());
		loginUser.setFlag(0);// 未审核前注册投标人默认状态未0
		try {
			this.rUserDao.saveRegisterUser(loginUser);
			result = Constant.REGISTER_SUCCESS_UN_COMPLETE;
			saveCategory(loginUser.getProjectCategory(), loginUser.getId());
		} catch (Exception e) {
			e.printStackTrace();
			result = Constant.REGISTER_UN_SUCCESS;
		}
		return result;
	}
	
//	@Override
//	@Transactional
//	public String updateRegisterUser(RegisterUser loginUser,RegisterUser oldRUser) {
//		String result = "";
//	//	loginUser.setCreateTime(oldRUser.getCreateTime());
//	//	loginUser.setUpdateTime(new Date());
//		oldRUser.setFlag(0);// 未审核前注册投标人默认状态未0
//		oldRUser.setUpdateTime(new Date());
//		oldRUser.setPost(loginUser.getPost());
//		
//		try {
//			this.saveOrUpdate(oldRUser);
//			result = Constant.REGISTER_SUCCESS_UN_COMPLETE;
//			saveCategory(loginUser.getProjectCategory(), loginUser.getId());
//		} catch (Exception e) {
//			e.printStackTrace();
//			result = Constant.REGISTER_UN_SUCCESS;
//		}
//		return result;
//	}

	public void saveCategory(String categories, String registerId) {
		if (StringUtils.isEmpty(categories)) {
			List<RegisterCategory> list = this.rUserDao.getRegisterCategory(registerId);
			if(list.size()>0){
				rUserDao.removeCategories(registerId);
			}
			return;
		}
		if (StringUtils.isEmpty(registerId)) {
			return;
		}
		if (!StringUtils.isEmpty(categories)) {
			rUserDao.removeCategories(registerId);
			System.out.println("删除已有类型！");
			saveCategries(categories, registerId);
		}
	}

	@Transactional
	public void saveCategries(String categories, String registerId) {
		for (String categoryId : categories.split(",")) {
			RegisterCategory rc = new RegisterCategory();
			rc.setCategoryId(categoryId);
			rc.setRegisterId(registerId);
			this.save(rc);
		}
	}

	@Override
	public Rsp getRegisterUserByLoginName(String loginName, String pwd) {
		Rsp rsp = new Rsp();
		String msg = "";
		RegisterUser registerUser = new RegisterUser();
		List<RegisterUser> list = this.rUserDao
				.findRegisterUserByLoginName(loginName);
		if (list.size() > 0) {
			registerUser = list.get(0);
			if (loginName.equals(registerUser.getLoginName())
					&& pwd.equals(registerUser.getPwd())) {
				rsp.setRows(registerUser);
			} else {
				msg = "您输入的密码不正确，请重新输入！";
			}
		} else {
			msg = "您的用户名不存在，请确认后重新输入！";
			rsp.setMsg(msg);
		}

		return rsp;
	}

	@Override
	public List<RegisterUser> getRegisterList(Page page,RegisterUser registerUser,java.sql.Date startTime,java.sql.Date endTime) {
		return this.rUserDao.getRegisterList(page,registerUser,startTime,endTime);
	}

	@Override
	@Transactional
	public Rsp auditRegister(User user, String registerId, String reason,int auth_flag) {
		Rsp rsp = new Rsp();
		RegisterUser rUser = new RegisterUser();
		if (!StringUtils.isEmpty(registerId)) {
			List<RegisterUser> list = this.rUserDao.getRegisterById(registerId);
			rUser = list.get(0);
			rUser.setReason(reason);
			rUser.setFlag(auth_flag);
			//SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			rUser.setUpdateTime(new Date());
			rUser.setAuditorId(user.getId());
			rUser.setAuditorName(user.getName());
			try {
				this.rUserDao.saveRegisterUser(rUser);

				rsp.setRows("审核完成！");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			rsp.setRows("注册用户id is null");
		}
		if (rUser.getFlag() == 1) {
			// 开始同步act_id_user表
			saveActivitiRegisterUser(rUser);
			// 添加act_id_membership 关联
			addMembershipToIdentify(rUser);
			
			try {
				copyToUser(rUser,user);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		return rsp;
	}

	@Override
	public RegisterUser getRegisterById(String id) {
		RegisterUser registerUser = new RegisterUser();
		List<RegisterUser> list = this.rUserDao.getRegisterById(id);
		registerUser = list.get(0);
		return registerUser;
	}

	@Override
	public List<RegisterUser> regcaLogin(String caName) {
		return this.rUserDao.regcaLogin(caName);
	}

	@Override
	public List<RegisterUser> findRegisterUserByLoginName(String loginName) {
		return this.rUserDao.findRegisterUserByLoginName(loginName);
	}
	
	@Override
	public List<RegisterUser> findRegisterUserByCompany(String company) {
		return this.rUserDao.findRegisterUserByLoginName(company);
	}

	@Override
	public String tenderforbid(User user, RegisterUser rUser) {
		String result = "";
		RegisterUser tempRegisterUser = new RegisterUser();
		if (rUser != null) {
			tempRegisterUser = this.getRegisterById(rUser.getId());
			//SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//	SimpleDateFormat time2 = new SimpleDateFormat("yyyy-MM-dd");
			tempRegisterUser.setUpdateTime(new Date());
			tempRegisterUser.setOperatorId(user.getId());
			tempRegisterUser.setOperatorName(user.getName());
			tempRegisterUser.setForbidEndDate(rUser.getForbidEndDate());
			tempRegisterUser.setForbidStartDate(new Date());
			tempRegisterUser.setForbidReason(rUser.getForbidReason());
			try {
				this.rUserDao.saveOrUpdateObject(tempRegisterUser);
				result = Constant.UPDATE_SUCCESS;
			} catch (Exception e) {
				e.printStackTrace();
				result = Constant.UPDATE_UN_SUCCESS;
			}
		}
		return result;
	}

	@Override
	public String tenderRecover(User user, RegisterUser rUser) {
		String result = "";
		RegisterUser tempRegisterUser = new RegisterUser();
		if (rUser != null) {
			tempRegisterUser = this.getRegisterById(rUser.getId());
		//	SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			tempRegisterUser.setUpdateTime(new Date());
			tempRegisterUser.setOperatorId(user.getId());
			tempRegisterUser.setOperatorName(user.getName());
			tempRegisterUser.setForbidEndDate(null);
			tempRegisterUser.setForbidStartDate(null);
			tempRegisterUser.setForbidReason(null);
			try {
				this.rUserDao.saveOrUpdateObject(tempRegisterUser);
				result = Constant.UPDATE_SUCCESS;
			} catch (Exception e) {
				e.printStackTrace();
				result = Constant.UPDATE_UN_SUCCESS;
			}
		}
		return result;
	}

	@Override
	public void searchList(Page page, String name, String loginName, int flag) {
		this.rUserDao.searchList(page, name, loginName, flag);
	}

	/**
	 * 添加一个用户到Activiti {@link org.activiti.engine.identity.User}
	 * 
	 * @param user
	 *            用户对象, {@link User}
	 */
	public void saveActivitiRegisterUser(RegisterUser user) {
		String userId = user.getId().toString();
		identityService.deleteUser(userId);
		org.activiti.engine.identity.User activitiUser = identityService.newUser(userId);
		cloneAndSaveActivitiUser(user, activitiUser);
	}

	/**
	 * 添加Activiti Identify的用户于组关系
	 *
	 *            用户ID
	 */
	public void addMembershipToIdentify(RegisterUser rUser) {
		String roleId = rUser.getType();
		String userId = rUser.getId();
		String groupId;
		groupId = CommUtil.getGroupId(roleId);
		identityService.deleteMembership(userId, groupId);
		identityService.createMembership(userId, groupId);
	}

	/**
	 * 使用系统用户对象属性设置到Activiti User对象中
	 *            系统用户对象
	 * @param activitiUser
	 *            Activiti User
	 */
	public void cloneAndSaveActivitiUser(RegisterUser rUser,org.activiti.engine.identity.User activitiUser) {
		activitiUser.setId(rUser.getId());
		identityService.saveUser(activitiUser);
	}

	@Override
	@Transactional
	public String setDepositCategory(String DepositCategoryIds,
			String registerId) {
		if (StringUtils.isEmpty(DepositCategoryIds)) {
			rUserDao.removeDepositCategories(registerId);
			return "保存成功！";
		}
		try {
			rUserDao.removeDepositCategories(registerId);
			System.out.println("删除已有类型！");
		} catch (Exception e) {
			return "保存失败!";
		}

		return saveDepositCategries(DepositCategoryIds, registerId);
	}
	
	/**
	 * 同步User表
	 * @author shy
	 * @param
	 * @return
	 * @throws ParseException 
	 */
	@Transactional
	public void copyToUser(RegisterUser rUser,User user) throws ParseException{
		List<User> users= this.userService.getLoginUserByLoginName(rUser.getLoginName());
		if(users.isEmpty()){		
		User u = new User();
		u.setLoginName(rUser.getLoginName());
		u.setName(rUser.getName());
		u.setPsw(rUser.getPwd());
		u.setRegisterId(rUser.getId());
		u.setCaCard(rUser.getCaCard());
		u.setEmail(rUser.getEmail());
		u.setSex(rUser.getSex());
		u.setCreaterId(user.getId());
		u.setCreaterName(user.getName());
		u.setDeptId(Constant.REGISTER_DEPT_ID);
		u.setCreateTime(rUser.getCreateTime());
		u.setPost(rUser.getPost());
		u.setLoginPWD(rUser.getLoginTypePWD());
		u.setLoginCA(rUser.getLoginTypeCA());
		this.saveOrUpdate(u);		
		UserRole userRole = new UserRole();
		userRole.setRoleId(rUser.getType());
		userRole.setUserId(u.getId());
		userRole.setCreaterName(user.getName());
		userRole.setCreaterId(user.getId());
		userRole.setCreateTime(new Date());
		this.saveOrUpdate(userRole);
		}else{
			User newUser = users.get(0);
			newUser.setName(rUser.getName());
			newUser.setCaCard(rUser.getCaCard());
			newUser.setEmail(rUser.getEmail());
			newUser.setSex(rUser.getSex());
			newUser.setPost(rUser.getPost());
			newUser.setCaCard(rUser.getCaCard());
			newUser.setDeptId(Constant.REGISTER_DEPT_ID);
			newUser.setUpdaterId(user.getId());
			newUser.setUpdaterName(user.getName());
			newUser.setUpdateTime(new Date());
			newUser.setRegisterId(rUser.getId());	
			newUser.setPsw(rUser.getPwd());
			newUser.setLoginPWD(rUser.getLoginTypePWD());
			newUser.setLoginCA(rUser.getLoginTypeCA());
			newUser.setCaCard(rUser.getCaCard());
			newUser.setFlag(0);
			this.saveOrUpdate(newUser);		
		}
	}


	public String saveDepositCategries(String categories, String registerId) {
		for (String categoryId : categories.split(",")) {
			DepositCategory dc = new DepositCategory();
			dc.setRegisterId(registerId);
			dc.setDepositCategoryId(categoryId);
			this.save(dc);
		}
		return Constant.BIND_SUCCESS;
	}

	@Override
	public String getDepositCategory(String registerId) {
		List<DepositCategory> list = rUserDao.getDepositCategory(registerId);
		StringBuilder DepositCategoryStr = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			if (i == list.size() - 1) {
				DepositCategoryStr.append(list.get(i).getDepositCategoryId());
			} else {
				DepositCategoryStr.append(list.get(i).getDepositCategoryId())
						.append(",");
			}
		}

		return DepositCategoryStr.toString();
	}

	@Override
	public String getDepositCategoryName(String registerId) {
		List<RegisterCategory> list = rUserDao.getRegisterCategory(registerId);
		StringBuilder DepositCategoryStr = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			if (i == list.size() - 1) {
				String id = list.get(i).getCategoryId();				
				String name = rUserDao.getProjectTypebyId(id).getName();
				DepositCategoryStr.append(name);
			} else {
				String id = list.get(i).getCategoryId();
				String name = rUserDao.getProjectTypebyId(id).getName();
				DepositCategoryStr.append(name).append(",");
			}
		}

		return DepositCategoryStr.toString();
	}

	@Override
	public List<RegisterUser> getLoginRegisterUserByLoginName(String loginName) {
		return this.rUserDao.getLoginRegisterUserByLoginName(loginName);
	}

	@Override
	public List<DepositCategory> getDepositCategoryById(String registerId) {
		
		return this.rUserDao.getDepositCategoryById(registerId);
	}

	@Override
	public List<RegisterCategory> getRegisterCategoryById(String registerId) {
		return  this.rUserDao.getRegisterCategory(registerId);
	}

	@Override
	public RegisterUser getRegisterByLoginname(String loginName) {
		
		return rUserDao.getRegisterByLoginname(loginName);
	}

	@Override
	public User getUserByRegisterId(String registerId) {
		
		return rUserDao.getUserByRegisterId(registerId);
	}

	@Override
	public List<RegisterUser> getSameAccountUser(String account) {
		return rUserDao.getSameAccountUser(account);
	}

	@Override
	public List<RegisterUser> getSameAccountUserExceptMyself(String account, String loginName) {
		return rUserDao.getSameAccountUserExceptMyself(account,loginName);
	}

}
